<?php

function __autoload($ten){
	$ten=str_replace("_","/",$ten);
	$ten=strtolower(str_replace("Model","Models",$ten));

	if(file_exists(BASE_PATH . "/$ten.php")){
		require ("$ten.php");
	}//else{
		//throw new Exception('Missing file');
	//}
	

}

function loadview($ten,$data=""){

	require("views/$ten.php");

}



function redirect($url){

	ob_end_clean();

	header("location:$url");

	exit();

}

function redirectjs($str,$url){

	loadview("template/header2");

	echo "<script>alert('".$str."');location.href='".$url."'</script>";

	exit();
}

function filter($string)
{
$string1=$string;
$thay='*';
return preg_replace("/(location\.)|(alert)|(document\.)|(script)|(implementation)|(livescript)|(LAYER)|(mocha)|(select)|(union)|(concat)/i", $thay, $string1);
}

if (get_magic_quotes_gpc()) {
 function stripslashes_deep($value)
 	{
       $value = is_array($value) ?
        array_map('stripslashes_deep', $value) :
                    stripslashes(filter($value));
        return $value;
	}  

	  $_POST =stripslashes_deep($_POST);
	  $_GET =stripslashes_deep($_GET);

}







 function khongdau($str) { 
	$str = preg_replace("(%20| )", '-', $str);
    $str = preg_replace("/(\.|\/|_|!|>|<|^|,|;|#|%|'|\"|\?|=)/", '', $str);  
    $str = str_replace('----','-',$str);  
    $str = str_replace('---','-',$str);  
    $str = str_replace('--','-',$str);  
    $str = str_replace(':','-',$str);
	$str = preg_replace("(\()", '', $str);
	$str = preg_replace("(\))", '', $str); 	
   $str = preg_replace("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/", 'a', $str);
	$str = preg_replace("/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/", 'e', $str);
	$str = preg_replace("/(ì|í|ị|ỉ|ĩ)/", 'i', $str);
	$str = preg_replace("/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/", 'o', $str);
	$str = preg_replace("/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/", 'u', $str);
	$str = preg_replace("/(ỳ|ý|ỵ|ỷ|ỹ)/", 'y', $str);
	$str = preg_replace("/(đ)/", 'd', $str);
	$str = preg_replace("/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/", 'A', $str);
	$str = preg_replace("/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/", 'E', $str);
	$str = preg_replace("/(Ì|Í|Ị|Ỉ|Ĩ)/", 'I', $str);
	$str = preg_replace("/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/", 'O', $str);
	$str = preg_replace("/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/", 'U', $str);
	$str = preg_replace("/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/", 'Y', $str);
	$str = preg_replace("/(Đ)/", 'D', $str);
	$str = preg_replace("/'/", '', $str); 
	$str = preg_replace("//", '', $str); 
	$str = preg_replace("/%/", '', $str); 
	return $str; 
}











function url() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}



function echo2($str)
{
	 echo htmlspecialchars($str,ENT_QUOTES,'utf-8');

}

function get_ip()
{
     $ip = false;
     if(!empty($_SERVER['HTTP_CLIENT_IP']))
     {
          $ip = $_SERVER['HTTP_CLIENT_IP'];
     }
     if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
     {
          $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
          if($ip)
          {
              array_unshift($ips, $ip);
               $ip = false;
          }
          for($i = 0; $i < count($ips); $i++)
          {
               if(!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i]))
               {
                    if(version_compare(phpversion(), "5.0.0", ">="))
                    {
                         if(ip2long($ips[$i]) != false)
                         {
                              $ip = $ips[$i];
                              break;
                        }

                    }

                    else

                    {

                         if(ip2long($ips[$i]) != - 1)
                         {
                              $ip = $ips[$i];
                             break;

                         }

                    }

               }

          }

     }

     return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

}  



function randomstring($length = 10) {
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}


function time_ago($date)
{

	if(empty($date)){
		return "No date provided";
	}

	$periods = array("giây", "phút", "giờ", "ngày", "tuần", "tháng", "năm", "10 năm");
	$lengths = array("60","60","24","7","4.35","12","10");
	$now = time();
	$unix_date = strtotime($date);
	
// check validity of date
	if(empty($unix_date)) {
	return "End day";
	}

// is it future date or past date

	if($now > $unix_date) {
	$difference = $now - $unix_date;
	$tense = "trước";
	} else {
	$difference = $unix_date - $now;
	$tense = "từ giờ";}
	for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
	$difference /= $lengths[$j];
	}
	$difference = round($difference);
	if($difference != 1) {
	$periods[$j].= "";
	}
	return "$difference $periods[$j] {$tense}";

}
function get_facebook_info($url){
$url2 = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($url);
$xml = file_get_contents($url2);
$xml = simplexml_load_string($xml);
$data['like'] = $xml->link_stat->like_count||0;
$data['comment']= $xml->link_stat->comment_count||0; 

return $data;
}



/**
 * Translates a number to a short alhanumeric version
 *
 * Translated any number up to 9007199254740992
 * to a shorter version in letters e.g.:
 * 9007199254740989 --> PpQXn7COf
 *
 * specifiying the second argument true, it will
 * translate back e.g.:
 * PpQXn7COf --> 9007199254740989
 *
 * this function is based on any2dec && dec2any by
 * fragmer[at]mail[dot]ru
 * see: http://nl3.php.net/manual/en/function.base-convert.php#52450
 *
 * If you want the alphaID to be at least 3 letter long, use the
 * $pad_up = 3 argument
 *
 * In most cases this is better than totally random ID generators
 * because this can easily avoid duplicate ID's.
 * For example if you correlate the alpha ID to an auto incrementing ID
 * in your database, you're done.
 *
 * The reverse is done because it makes it slightly more cryptic,
 * but it also makes it easier to spread lots of IDs in different
 * directories on your filesystem. Example:
 * $part1 = substr($alpha_id,0,1);
 * $part2 = substr($alpha_id,1,1);
 * $part3 = substr($alpha_id,2,strlen($alpha_id));
 * $destindir = "/".$part1."/".$part2."/".$part3;
 * // by reversing, directories are more evenly spread out. The
 * // first 26 directories already occupy 26 main levels
 *
 * more info on limitation:
 * - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/165372
 *
 * if you really need this for bigger numbers you probably have to look
 * at things like: http://theserverpages.com/php/manual/en/ref.bc.php
 * or: http://theserverpages.com/php/manual/en/ref.gmp.php
 * but I haven't really dugg into this. If you have more info on those
 * matters feel free to leave a comment.
 *
 * The following code block can be utilized by PEAR's Testing_DocTest
 * <code>
 * // Input //
 * $number_in = 2188847690240;
 * $alpha_in  = "SpQXn7Cb";
 *
 * // Execute //
 * $alpha_out  = alphaID($number_in, false, 8);
 * $number_out = alphaID($alpha_in, true, 8);
 *
 * if ($number_in != $number_out) {
 *	 echo "Conversion failure, ".$alpha_in." returns ".$number_out." instead of the ";
 *	 echo "desired: ".$number_in."\n";
 * }
 * if ($alpha_in != $alpha_out) {
 *	 echo "Conversion failure, ".$number_in." returns ".$alpha_out." instead of the ";
 *	 echo "desired: ".$alpha_in."\n";
 * }
 *
 * // Show //
 * echo $number_out." => ".$alpha_out."\n";
 * echo $alpha_in." => ".$number_out."\n";
 * echo alphaID(238328, false)." => ".alphaID(alphaID(238328, false), true)."\n";
 *
 * // expects:
 * // 2188847690240 => SpQXn7Cb
 * // SpQXn7Cb => 2188847690240
 * // aaab => 238328
 *
 * </code>
 *
 * @author	Kevin van Zonneveld <kevin@vanzonneveld.net>
 * @author	Simon Franz
 * @author	Deadfish
 * @copyright 2008 Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD Licence
 * @version   SVN: Release: $Id: alphaID.inc.php 344 2009-06-10 17:43:59Z kevin $
 * @link	  http://kevin.vanzonneveld.net/
 *
 * @param mixed   $in	  String or long input to translate
 * @param boolean $to_num  Reverses translation when true
 * @param mixed   $pad_up  Number or boolean padds the result up to a specified length
 * @param string  $passKey Supplying a password makes it harder to calculate the original ID
 *
 * @return mixed string or long
 */

function alphaID($in, $to_num = false, $pad_up = false, $passKey = null)
{
	if(!$pad_up) $pad_up = 7;
	if(!$passKey) $passKey = 'keme';
	$index = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	if ($passKey !== null) {
		// Although this function's purpose is to just make the
		// ID short - and not so much secure,
		// with this patch by Simon Franz (http://blog.snaky.org/)
		// you can optionally supply a password to make it harder
		// to calculate the corresponding numeric ID

		for ($n = 0; $n<strlen($index); $n++) {
			$i[] = substr( $index,$n ,1);
		}

		$passhash = hash('sha256',$passKey);
		$passhash = (strlen($passhash) < strlen($index))
			? hash('sha512',$passKey)
			: $passhash;

		for ($n=0; $n < strlen($index); $n++) {
			$p[] =  substr($passhash, $n ,1);
		}

		array_multisort($p,  SORT_DESC, $i);
		$index = implode($i);
	}

	$base  = strlen($index);

	if ($to_num) {
		// Digital number  <<--  alphabet letter code
		$in  = strrev($in);
		$out = 0;
		$len = strlen($in) - 1;
		for ($t = 0; $t <= $len; $t++) {
			$bcpow = bcpow($base, $len - $t);
			$out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
		}

		if (is_numeric($pad_up)) {
			$pad_up--;
			if ($pad_up > 0) {
				$out -= pow($base, $pad_up);
			}
		}
		$out = sprintf('%F', $out);
		$out = substr($out, 0, strpos($out, '.'));
	} else {
		// Digital number  -->>  alphabet letter code
		if (is_numeric($pad_up)) {
			$pad_up--;
			if ($pad_up > 0) {
				$in += pow($base, $pad_up);
			}
		}

		$out = "";
		for ($t = floor(log($in, $base)); $t >= 0; $t--) {
			$bcp = bcpow($base, $t);
			$a   = floor($in / $bcp) % $base;
			$out = $out . substr($index, $a, 1);
			$in  = $in - ($a * $bcp);
		}
		$out = strrev($out); // reverse
	}

	return $out;
}

function url_post($id){
return HOME."post/".alphaID($id);
}
function url_album($id){
return HOME."album/".alphaID($id,false,8,'keme');
}
function url_category($id,$str){
return HOME. $str . '/' . alphaID($id, false).'.html';
}
function url_user($id){
return HOME."user/".$id;
}

function url_encode_post($id){
	return alphaID($id);
}
function url_decode_post($id){
	return alphaID($id,true);
}

function url_decode($id,$type){
	switch($type){
	 case 'post': 
	 return alphaID($id,true); break;
	 case 'album' : return alphaID($id,true,8,'keme');
	 break;
	}
}

function web_title($str,$where){
	switch($where){
		case 'home':
				if(isset($_GET['ext'])){
						$str.=' - '.$_GET['ext'].' '.$_GET['sort'];
					}
				if(isset($_GET['page']) && $_GET['page']!=''){
					$str.= ' - Trang '.$_GET['page'];
				}
				break;
		case 'category':
					if(isset($_GET['type'])){
							switch($_GET['type']){
								case 'hinh-anh': $str.=' - Hình ảnh'; break;
								case 'video': $str.=' - Video Clip'; break;
								case 'blog': $str.=' - Tin Tức'; break;
							}
					}
		
				if(isset($_GET['ext'])){
						$str.=' - '.$_GET['ext'].' '.$_GET['sort'];
					}
				if(isset($_GET['page'])){
					$str.= ' - Trang '.$_GET['page'];
				}
				break;	
				
				case 'type':
					if(isset($_GET['type'])){
							switch($_GET['type']){
								case 'hinh-anh': $str='Hình ảnh'; break;
								case 'video': $str='Video Clip'; break;
								case 'blog': $str='Blog'; break;
							}
					}
		
					if(isset($_GET['ext'])){
							$str.=' - '.$_GET['ext'].' '.$_GET['sort'];
						}
					if(isset($_GET['page'])){
						$str.= ' - Trang '.$_GET['page'];
					}
					break;	
				
			 case 'user':
					if(isset($_GET['ext'])){
							switch($_GET['ext']){
								case 'picture': $str.=' - Hình ảnh'; break;
								case 'video': $str.=' - Video Clip'; break;
								case 'text': $str.=' - Tin Tức'; break;
								case 'album': $str.=' - Album'; break;
							}
					}
		
				
				if(isset($_GET['page'])){
					$str.= ' - Trang '.$_GET['page'];
				}
				break;
				
		 case 'album':
								
				if(isset($_GET['page'])){
					$str.= ' - Trang '.$_GET['page'];
				}
				break;							
				
	}
	return $str;

}

function show_username($user,$name){
	if($name !='') return $name;
	return $user;
}

function url_ajax(){

	$url=url();
	if(!isset($_GET['page'])){
	return $url();
	}else{
		//Cat cai get page o cuoi di 
		
	}
}

